package com.imist.PipelineAndChannelHandler.client;

import com.imist.PipelineAndChannelHandler.protocol.Packet;
import com.imist.PipelineAndChannelHandler.protocol.PacketCodeC;
import com.imist.PipelineAndChannelHandler.protocol.request.LoginRequestPacket;
import com.imist.PipelineAndChannelHandler.protocol.response.LoginResponsePacket;
import com.imist.PipelineAndChannelHandler.protocol.response.MessageResponsePacket;
import com.imist.PipelineAndChannelHandler.utils.LoginUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Date;
import java.util.UUID;


public class ClientHandler extends ChannelInboundHandlerAdapter {
    /**
     * 客户端连接成功之后调用
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(new Date() +" : 客户端开始登陆");

        //创建登陆对象
        LoginRequestPacket loginRequestPacket = new LoginRequestPacket();
        loginRequestPacket.setUserId(UUID.randomUUID().toString());
        loginRequestPacket.setUsername("iMisty");
        loginRequestPacket.setPassword("123456");
        //编码
        ByteBuf buf  = PacketCodeC.INSTANCE.encode(ctx.alloc(),loginRequestPacket);
        //写数据
        ctx.channel().writeAndFlush(buf);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        Packet packet = PacketCodeC.INSTANCE.decode(byteBuf);
        if (packet instanceof LoginResponsePacket){
            LoginResponsePacket loginResponsePacket = (LoginResponsePacket) packet;
            if (loginResponsePacket.isSuccess()){
                LoginUtils.markAsLogin(ctx.channel());
                System.out.println(new Date()+" : 客户端的登陆成功...");
            }else {
                System.out.println(new Date()+" : 客户端登陆失败...原因是:"+loginResponsePacket.getReason());
            }
        } else if (packet instanceof MessageResponsePacket){
            MessageResponsePacket messageResonsePacket = (MessageResponsePacket) packet;
            System.out.println(new Date() + " : 收到服务端消息:  " + messageResonsePacket.getMessage());
        }
    }
}
